package com.asking.service;

import com.asking.dao.QuestionMapper;
import com.asking.domain.Answer;
import com.asking.domain.Question;
import com.asking.pojo.EsQuestion;
import com.asking.service.es.QuestionRepository;
import com.asking.vo.ResultVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: 宋定鑫
 * @Date: 2018/10/17 15:43
 */
@Service
@Transactional
public class QuestionService {

    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private QuestionRepository  questionRepository;
    public void add(Question question) {
        question.setTime(new Date());
        questionMapper.insert(question);
        EsQuestion  esQuestion=new EsQuestion();
        BeanUtils.copyProperties(question,esQuestion);
        questionRepository.save(esQuestion);
    }

    public void updata(Question question) {
        Question question1 = questionMapper.selectByPrimaryKey(question.getId());
        question.setTime(question1.getTime());
        EsQuestion  esQuestion=new EsQuestion();
        BeanUtils.copyProperties(question,esQuestion);
        questionMapper.updateByPrimaryKey(question);
        questionRepository.save(esQuestion);
    }

    public EsQuestion selectByAnswer(Integer id) {
        Question question = questionMapper.selectByPrimaryKey(id);
        Optional<EsQuestion> byId = questionRepository.findById(id);
        return byId.get();
    }
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public ResultVo findAll(Integer page, Integer rows,String title ) {
        NativeSearchQueryBuilder builder=new NativeSearchQueryBuilder();
        //创建一个booleanQuery
        BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();

        if(StringUtils.isNotBlank(title)){
            WildcardQueryBuilder QueryBuilder = QueryBuilders.wildcardQuery("title", "*" +title + "*");
            QueryStringQueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(title).field("title").defaultOperator(Operator.AND);
            BoolQueryBuilder boolQuery= QueryBuilders.boolQuery().should(QueryBuilder).should(queryStringQueryBuilder);
            boolQueryBuilder.should(boolQuery);

            WildcardQueryBuilder QB = QueryBuilders.wildcardQuery("text", "*" +title + "*");
            QueryStringQueryBuilder queryStringQueryBuilders= new QueryStringQueryBuilder(title).field("text").defaultOperator(Operator.AND);
            BoolQueryBuilder boolQuerys= QueryBuilders.boolQuery().should(QB).should(queryStringQueryBuilders);
            boolQueryBuilder.should(boolQuerys);
        }
        //设置高亮显示
      /*  HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);
        highlightBuilder.preTags("<span style=\"color:red\">");
        highlightBuilder.postTags("</span>");
        SearchRequestBuilder searchRequestBuilder = elasticsearchTemplate.getClient().prepareSearch("province")
                .setTypes("question")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) //设置查询类型：1.SearchType.DFS_QUERY_THEN_FETCH 精确查询； 2.SearchType.SCAN 扫描查询,无序
                .setQuery(boolQueryBuilder);
        searchRequestBuilder.highlighter(highlightBuilder);
        SearchResponse response = searchRequestBuilder.get();
        //接受结果
        List<Map<String, Object>> result = new ArrayList<>();
        //遍历结果
        for (SearchHit hit : response.getHits()) {
            Map<String, Object> source = hit.getSource();
            //处理高亮片段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField nameField = highlightFields.get("title");
            if (nameField != null) {
                Text[] fragments = nameField.fragments();
                String nameTmp = "";
                for (Text text : fragments) {
                    nameTmp += text;
                }
                //将高亮片段组装到结果中去
                source.put("title", nameTmp);
            }
            result.add(source);
        }*/
        builder.withPageable(PageRequest.of(page-1,rows));
        builder.withQuery(boolQueryBuilder);
        Page<EsQuestion> search = questionRepository.search(builder.build());
        ResultVo   resultVo=new ResultVo();
        resultVo.setTotal(search.getTotalElements());
        resultVo.setRows(search.getContent());
        return resultVo;
    }

    public void deleteidquestion(Integer id) {
        questionMapper.deleteByPrimaryKey(id);
        questionRepository.deleteById(id);
    }


    public void pare() {
        List<Question> questions = questionMapper.selectAll();

        List<EsQuestion> esQuestions = new ArrayList<>();
       for (Question  question:questions){
           EsQuestion  esQuestion=new EsQuestion();
           BeanUtils.copyProperties(question,esQuestion);
           esQuestions.add(esQuestion);
       }
        this.questionRepository.deleteAll();
        questionRepository.saveAll(esQuestions);

    }
}
